﻿using Loong.Domain.Uow;
using Loong.Threading.Locks;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Loong.BackgroundJobs
{
    public class BackgroundJobStore : IBackgroundJobStore
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly ILockFactory _lockFactory;
        private readonly BackgroundJobDbAccessor _backgroundJobDbAccessor;

        public BackgroundJobStore(
            IUnitOfWorkManager unitOfWorkManager,
            ILockFactory lockFactory,
            BackgroundJobDbAccessor backgroundJobDbAccessor)
        {
            _unitOfWorkManager = unitOfWorkManager;
            _lockFactory = lockFactory;
            _backgroundJobDbAccessor = backgroundJobDbAccessor;
        }

        public async Task<BackgroundJobInfo> GetAndLockWaitingJobAsync()
        {
            using (await _lockFactory.LockAsync("GetAndLockWaitingJob", _lockFactory.GetOrCreateOwner()))
            {
                using (var uow = _unitOfWorkManager.Begin())
                {
                    var waitingJob = await GetWaitingJobAsync();

                    if (waitingJob != null)
                    {
                        waitingJob.IsLocked = true;
                        waitingJob.LockEndTime = DateTime.Now.AddMinutes(30);
                    }

                    await uow.CompleteAsync();

                    return waitingJob;
                }
            }
        }

        private async Task<BackgroundJobInfo> GetWaitingJobAsync()
        {
            var now = DateTime.Now;

            var job = await _backgroundJobDbAccessor.Context.BackgroundJobs
                .Where(e => e.NextTryTime <= now)
                .Where(e => e.IsLocked == false || (e.IsLocked && e.LockEndTime <= now))
                .Where(e => e.IsAbandoned == false)
                .OrderByDescending(e => e.Priority)
                .ThenBy(e => e.TryCount)
                .ThenBy(e => e.NextTryTime)
                .FirstOrDefaultAsync();

            return job;
        }

        public async Task InsertJobAsync(BackgroundJobInfo jobInfo)
        {
            await SaveAsync(jobInfo);
        }

        public async Task UpdateJobAsync(BackgroundJobInfo jobInfo)
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                await SaveAsync(jobInfo);

                await uow.CompleteAsync();
            }
        }

        public async Task DeleteJobAsync(BackgroundJobInfo jobInfo)
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                await DeleteJobAsync(jobInfo.Id);

                await uow.CompleteAsync();
            }
        }

        public async Task DeleteJobAsync(long jobId)
        {
            await _backgroundJobDbAccessor.DeleteAsync(jobId);
        }

        public async Task<BackgroundJobInfo> SaveAsync(BackgroundJobInfo entity)
        {
            if (entity.IsTransient())
            {
                await _backgroundJobDbAccessor.Context.BackgroundJobs.AddAsync(entity);
            }
            else
            {
                await _backgroundJobDbAccessor.UpdateAsync(entity);
            }

            return entity;
        }
    }
}
